// admin/system/service/user_service.go
package service

import (
	repo "go-admin1/admin/system/dao"
	"go-admin1/admin/system/model"
	constants "go-admin1/internal/common/constant"
	"go-admin1/internal/exception"
	"go-admin1/internal/infrastructure/cache"
	"time"

	"github.com/mojocn/base64Captcha"
)

const (
	UserCachePrefix = "user:id:"
	UserCacheExpire = time.Hour
)

// UserService 用户服务接口
type UserService interface {
	CreateUser(user *model.User) error
	GetUserByID(id uint64) (*model.User, error)
	GetUserByUsername(username string) (*model.User, error)
	UpdateUser(user *model.User) error
	DeleteUser(id uint64) error
	ListUsers(page, pageSize int) ([]*model.User, int64, error)
	CheckUsernameExists(username string) (bool, error)
	GetUserByIDWithCache(id uint64) (*model.User, error)
	VerifyCaptcha(uuid string, code string) bool
}

type userService struct {
	userRepo repo.UserRepository
}

// NewUserService 创建用户服务实例
func NewUserService() UserService {
	return &userService{
		userRepo: repo.NewUserRepository(),
	}
}

func (s *userService) CreateUser(user *model.User) error {
	// 检查用户名是否已存在
	exists, err := s.CheckUsernameExists(user.Username)
	if err != nil {
		return err
	}
	if exists {
		return exception.NewBusinessError(400, "用户名已存在")
	}

	return s.userRepo.Create(user)
}

func (s *userService) GetUserByID(id uint64) (*model.User, error) {
	return s.userRepo.GetByID(id)
}

func (s *userService) GetUserByUsername(username string) (*model.User, error) {
	return s.userRepo.GetByUsername(username)
}

func (s *userService) UpdateUser(user *model.User) error {
	// 先更新数据库
	if err := s.userRepo.Update(user); err != nil {
		return err
	}

	// 清除缓存
	cacheKey := UserCachePrefix + string(rune(user.ID))
	cache.Delete(cacheKey)

	return nil
}

func (s *userService) DeleteUser(id uint64) error {
	// 先删除数据库记录
	if err := s.userRepo.Delete(id); err != nil {
		return err
	}

	// 清除缓存
	cacheKey := UserCachePrefix + string(rune(id))
	cache.Delete(cacheKey)

	return nil
}

func (s *userService) ListUsers(page, pageSize int) ([]*model.User, int64, error) {
	return s.userRepo.List(page, pageSize)
}

func (s *userService) CheckUsernameExists(username string) (bool, error) {
	_, err := s.userRepo.GetByUsername(username)
	if err != nil {
		// 如果是记录未找到错误，说明用户不存在
		if err.Error() == "record not found" {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func (s *userService) GetUserByIDWithCache(id uint64) (*model.User, error) {
	cacheKey := UserCachePrefix + string(rune(id))

	// 先尝试从缓存获取
	var user model.User
	if err := cache.GetStruct(cacheKey, &user); err == nil {
		return &user, nil
	}

	// 缓存未命中，从数据库获取
	userPtr, err := s.userRepo.GetByID(id)
	if err != nil {
		return nil, err
	}

	// 存入缓存
	cache.Set(cacheKey, userPtr, UserCacheExpire)

	return userPtr, nil
}

func (s *userService) VerifyCaptcha(uuid string, code string) bool {

	// 构造Redis键
	verifyKey := constants.CAPTCHA_CODE_KEY + uuid

	// 从Redis获取验证码ID
	captchaId, err := cache.Get(verifyKey)
	if err != nil || captchaId == "" {
		return false
	}
	// 使用默认存储验证验证码
	store := base64Captcha.DefaultMemStore
	if store.Verify(captchaId, code, true) {
		// 验证成功后删除验证码
		cache.Delete(verifyKey)
		return true
	}
	return false
}
